package com.ljph.jfinal.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jfinal.json.Json;

/**
 * Json 转换 fastjson 实现高级定制版.
 * Created by yuzhou on 16/8/16.
 */
public class EnhancedFastJson extends Json {

    public EnhancedFastJson setFilter(SerializeFilter filter) {
        this.filter = filter;
        return this;
    }

    protected SerializeFilter filter = null;

    public static EnhancedFastJson getJson() {
        return new EnhancedFastJson();
    }

    @Override
    public String toJson(Object object) {
        // 优先使用对象级的属性 datePattern, 然后才是全局性的 defaultDatePattern
        String dp = datePattern != null ? datePattern : getDefaultDatePattern();
        if (dp == null) {
            if(filter != null) {
                return JSON.toJSONString(object, new SerializeFilter[] {filter});
            }
            return JSON.toJSONString(object);
        } else {
            return JSON.toJSONStringWithDateFormat(object, dp, SerializerFeature.WriteDateUseDateFormat);	// return JSON.toJSONString(object, SerializerFeature.WriteDateUseDateFormat);
        }
    }

    @Override
    public <T> T parse(String jsonString, Class<T> type) {
         return JSON.parseObject(jsonString, type);
    }
}
